#include "smart_config.h"
#include <sstream> // 支持 isWifiConnected 的 std::istringstream

// 添加多線程名稱日志記錄
// 檢查連接wifi，線程卡住

// 全局退出信号
std::atomic<bool> g_exit_event(false);

// 构造函数：初始化日志文件和成员变量
SmartConfig::SmartConfig()
    : is_active(false),
      total_len(0),
      total_len_count(0),
      current_index(-1),
      has_check_repeat_flag(false),
      INTERFACE("wlan0mon"),
      BROADCAST_MAC("ff:ff:ff:ff:ff:ff"),
      ASCII_START(127),
      ASCII_END(128),
      pcap_handle(nullptr),
      done(false) {
    // log("➡️ 进入函数: SmartConfig::SmartConfig");
    logger.open("/var/log/smart_config.log", std::ios::app);
    if (!logger.is_open()) {
        std::cerr << "❌ 无法打开日志文件" << std::endl;
    }
}

// 析构函数：关闭日志文件和 pcap 句柄
SmartConfig::~SmartConfig() {
    // log("➡️ 开始析构...");
    
    // 1. 先设置停止标志
    done = true;
    g_exit_event = true;
    
    // 2. 立即停止 pcap 捕获
    if (pcap_handle) {
        pcap_breakloop(pcap_handle);
        pcap_close(pcap_handle);  // 直接关闭，强制中断
        pcap_handle = nullptr;
    }
    
    // 3. 通知所有等待线程
    targetDataCV.notify_all();
    queueCV.notify_all();
    
    // 4. 等待所有线程结束
    if (captureThread.joinable()) {
        // log("等待捕获线程结束...");
        captureThread.join();
    }
    
    for (auto& t : processThreads) {
        if (t.joinable()) {
            // log("等待处理线程结束...");
            t.join();
        }
    }
    
    if (sniffing_thread.joinable()) {
        // log("等待嗅探线程结束...");
        sniffing_thread.join();
    }
    
    // 5. 清理网络接口
    if (INTERFACE == "wlan0mon") {
        // log("清理监控模式接口...");
        system("airmon-ng stop wlan0mon");
        system("systemctl start NetworkManager");
    }
    
    // 6. 关闭pcap句柄
    if (pcap_handle) {
        // log("关闭pcap句柄...");
        pcap_close(pcap_handle);
        pcap_handle = nullptr;
    }
    
    // 7. 关闭日志
    if (logger.is_open()) {
        // log("关闭日志文件...");
        logger.close();
    }
    
    // log("✅ 析构完成");
    exit(0);
}

// 检查是否以 root 权限运行
void SmartConfig::checkRoot() {
    // log("➡️ 进入函数: checkRoot");
    if (geteuid() != 0) {
        // log("❌ 错误：需要 root 权限！");
        exit(1);
    }
}

// 检查是否已连接到 WiFi 网络
bool SmartConfig::isWifiConnected() {
    // log("➡️ 进入函数: isWifiConnected");
    FILE* fp = popen("nmcli -t -f DEVICE,STATE device status 2>/dev/null", "r");
    if (!fp) {
        perror("popen failed");
        return false;
    }

    char buf[256];
    bool connected = false;

    while (fgets(buf, sizeof(buf), fp)) {
        std::string line(buf);
        std::istringstream iss(line);
        std::string device, state;

        if (std::getline(iss, device, ':') && std::getline(iss, state, ':')) {
            size_t pos = state.find_last_not_of(" \n\r\t");
            if (pos != std::string::npos) {
                state.erase(pos + 1);
            } else {
                state.clear();
            }
            if ((device == "wlan0" || device.find("wl") == 0) && state == "connected") {
                connected = true;
                break;
            }
        }
    }
    
    pclose(fp);
    return connected;
}

// 将 ASCII 码转换为可打印字符
char SmartConfig::asciiChar(int code) {
    // // log("➡️ 进入函数: asciiChar");
    if (code >= 32 && code <= 126) {
        return static_cast<char>(code);
    }
    return 0;
}

// 重置嗅探状态和数据
void SmartConfig::reset() {
    // log("➡️ 进入函数: reset");
    is_active = false;
    frame_data.clear();
    has_check_repeat_flag = false;
}

// 解析 WiFi 凭证（格式：SSID:password）
std::pair<std::string, std::string> SmartConfig::parseWifiCredentials(const std::string& credentialsStr) {
    // log("➡️ 进入函数: parseWifiCredentials");
    size_t pos = credentialsStr.find(':');
    if (pos != std::string::npos) {
        std::string ssid = credentialsStr.substr(0, pos);
        std::string password = credentialsStr.substr(pos + 1);
        char buffer[256];
        snprintf(buffer, sizeof(buffer), "SSID: %s, PassWord: %s", 
                ssid.c_str(), password.c_str());
        // log(buffer);
        return std::make_pair(ssid, password);
    }
    throw std::invalid_argument("无效的凭证格式");
}

// 切换到托管模式
void SmartConfig::switchToManaged(const std::string& monitorIface, const std::string& managedIface) {
    // log("➡️ 进入函数: switchToManaged");
    // log("📡 停止监控模式接口: " + monitorIface);
    system(("airmon-ng stop " + monitorIface).c_str());
    // log("🔄 设置接口 " + managedIface + " 为托管模式");
    system(("ip link set " + managedIface + " down").c_str());
    system(("iw " + managedIface + " set type managed").c_str());
    system(("ip link set " + managedIface + " up").c_str());
    // log("🔄 启动 NetworkManager");
    system("systemctl start NetworkManager");
    sleep(5);
    INTERFACE = managedIface;
    // log("✅ 已切换到托管模式: " + managedIface);
}

// 切换到监控模式
bool SmartConfig::switchToMonitor(const std::string& managedIface, const std::string& monitorIface, int timeout, int channel) {
    // log("➡️ 进入函数: switchToMonitor");
    // log("🔄 停止 NetworkManager");
    system("airmon-ng check kill");
    sleep(3);
    
    // 使用传入的channel参数
    system(("airmon-ng start " + managedIface + " " + std::to_string(channel)).c_str());
    
    for (int i = 0; i < timeout; ++i) {
        if (access(("/sys/class/net/" + monitorIface).c_str(), F_OK) != -1) {
            FILE* fp = popen(("iwconfig " + monitorIface).c_str(), "r");
            if (fp) {
                char buf[1024];
                while (fgets(buf, sizeof(buf), fp)) {
                    if (strstr(buf, "Mode:Monitor")) {
                        pclose(fp);
                        INTERFACE = monitorIface;
                        // log("✅ 监控模式启动成功 | 接口: " + monitorIface + " | 信道: " + std::to_string(channel));
                        return true;
                    }
                }
                pclose(fp);
            }
        }
        sleep(1);
    }
    
    // log("❌ 超时: " + monitorIface + " 未在 " + std::to_string(timeout) + " 秒内进入监控模式");
    return false;
}

// 广播 ACK 消息
void SmartConfig::broadcastAck(int port, const std::string& ackMessage) {
    // log("➡️ 进入函数: broadcastAck");
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        // log("❌ 创建套接字失败");
        return;
    }
    int broadcastEnable = 1;
    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = inet_addr("255.255.255.255");
    for (int i = 0; i < 10; ++i) {
        sendto(sock, ackMessage.c_str(), ackMessage.size(), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
        // log("✅ 广播 ACK 到 255.255.255.255:" + std::to_string(port));
    }
    close(sock);
}

// 初始化 libpcap
void SmartConfig::initializePcap() {
    // log("➡️ 进入函数: initializePcap");
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_handle = pcap_open_live(INTERFACE.c_str(), 65535, 1, 1000, errbuf);
    if (pcap_handle == nullptr) {
        // log("❌ 无法打开 pcap: " + std::string(errbuf));
        exit(1);
    }
}

// 启动数据包嗅探
void SmartConfig::startSniffing() {
    // log("➡️ 进入函数: startSniffing");
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_handle = pcap_open_live(INTERFACE.c_str(), 65535, 1, 100, errbuf);
    if (!pcap_handle) {
        // log("❌ 无法打开 pcap: " + std::string(errbuf));
        return;
    }
    struct bpf_program fp;
    if (pcap_compile(pcap_handle, &fp, "type data", 0, PCAP_NETMASK_UNKNOWN) == -1) {
        // log("❌ 编译BPF过滤器错误: " + std::string(pcap_geterr(pcap_handle)));
        return;
    }
    if (pcap_setfilter(pcap_handle, &fp) == -1) {
        // log("❌ 设置BPF过滤器错误: " + std::string(pcap_geterr(pcap_handle)));
        pcap_freecode(&fp);
        return;
    }
    pcap_freecode(&fp);
    // 启动捕获线程并命名
    captureThread = std::thread([this]() {
        {
            std::lock_guard<std::mutex> lock(threadNamesMutex);
            threadNames[std::this_thread::get_id()] = "捕获线程";
        }
        capturePackets(this->pcap_handle);
    });

    // 启动处理线程并命名
    for (int i = 0; i < 1; ++i) {
        processThreads.emplace_back([this, i]() {
            {
                std::lock_guard<std::mutex> lock(threadNamesMutex);
                threadNames[std::this_thread::get_id()] = "处理线程-" + std::to_string(i + 1);
            }
            processPackets();
        });
    }
    // log("🛑 嗅探线程退出");
}

void SmartConfig::capturePackets(pcap_t* handle) {
    // log("开始捕获数据包");
    while (!done) {
        struct pcap_pkthdr* header;
        const u_char* packet;
        
        // 设置超时为100ms，这样能及时检查 done 标志
        if (pcap_set_timeout(handle, 100) != 0) {
            // log("设置超时失败");
        }
        
        int res = pcap_next_ex(handle, &header, &packet);
        if (res == 0) {  // 超时
            continue;
        }
        if (res > 0) {
            std::vector<u_char> packetCopy(packet, packet + header->caplen);
            std::lock_guard<std::mutex> lock(queueMutex);
            packetQueue.emplace(*header, std::move(packetCopy));
            queueCV.notify_all();
        }
        if (res == -1) {
            // log("捕获错误: " + std::string(pcap_geterr(handle)));
            break;
        }
    }
    // log("停止捕获数据包");
}

void SmartConfig::processPackets() {
    // log("开始处理数据包");
    while (!done) {
        std::unique_lock<std::mutex> lock(queueMutex);
        queueCV.wait(lock, [this] { return !packetQueue.empty() || done; });
        if (!packetQueue.empty()) {
            auto [header, packet] = std::move(packetQueue.front());
            packetQueue.pop();
             // 在取出数据后打印队列剩余长度
            // log("📦 packetQueue 剩余长度: " + std::to_string(packetQueue.size()));
            lock.unlock();
            processPacket(&header, packet.data());
        }
    }
    // log("停止处理数据包");
}

// 处理捕获的数据包
void SmartConfig::processPacket(const struct pcap_pkthdr* pkthdr, const u_char* packet) {
    std::lock_guard<std::mutex> lock(dataMutex);
    // // log("➡️ 进入函数: processPacket");
    // 检查帧长度
    if (pkthdr->len < HEADER_LEN) {
        // // log("❌ 帧长度过短: " + std::to_string(pkthdr->len));
        return;
    }
    uint16_t radiotap_len = le16toh(*(reinterpret_cast<const uint16_t*>(packet + 2)));
    // 验证长度有效性
    if (pkthdr->caplen < radiotap_len + 24) return; // 确保足够读取802.11帧头
    // 定位到真正的802.11帧起始位置
    const u_char* dot11 = packet + radiotap_len;
    
    // 提取帧控制字段（此时值应为0x6208）
    uint16_t frame_control = *reinterpret_cast<const uint16_t*>(dot11); // 直接读取小端序值
    // // log("🔢 frame_control: 0x" + std::to_string(frame_control));
    uint8_t type = (frame_control >> 2) & 0x3;
    if (type != 2) {
        // log("❌ 非数据帧，类型: " + std::to_string(type));
        return;
    }
    // 检查目标地址
    const u_char* addr1 = dot11 + 4;
    if (memcmp(addr1, "\xff\xff\xff\xff\xff\xff", 6) != 0) {
        // log("❌ 非广播地址");
        return;
    }
    // 获取并打印 frame_len
    int frame_len = pkthdr->len;
    // log("📏 frame_len: " + std::to_string(frame_len));
    if (frame_len < HEADER_LEN) {
        // log("❌ 帧长度小于 HEADER_LEN: " + std::to_string(frame_len));
        return;
    }
    int ascii_code = frame_len - HEADER_LEN;
    // log("🌐 捕获帧 (总长度: " + std::to_string(frame_len) + ", ascii_code: " + std::to_string(ascii_code) + ")");
    frame_data.push_back(ascii_code);
    size_t frame_data_len = frame_data.size();

    if (ascii_code == ASCII_START) {
        if (frame_data_len > 1) {
            reset();
            frame_data.push_back(ascii_code);
        }
        is_active = true;
        return;
    }

    if (ascii_code == ASCII_END) {
        // log("🛑 检测到结束帧");
        // // log("📋 帧数据: " + vectorToString(frame_data));
        // // log("📝 解码结果: " + mapToString(data_dict));
        // // log("🔢 总长度计数: " + std::to_string(total_len_count));
        // // log("📊 总长度候选: " + vectorToString(total_len_list));

        reset();
        return;
    }

    if (!is_active) return;

    if (frame_data_len > 5) {
        // log("⚠️ 帧数量过多，重置");
        reset();
        return;
    }

    if (frame_data_len == 2) {
        int temp_len = ascii_code;
        // log("📏 当前总长度: " + std::to_string(temp_len));
        if (total_len_count < 5) {
            total_len_list.push_back(temp_len);
            total_len_count++;
        } else if (total_len_count >= 5 && total_len == 0) {
            std::map<int, int> countMap;
            for (int val : total_len_list) {
                countMap[val]++;
            }
            int maxCount = 0;
            int bestLen = 0;
            for (const auto& pair : countMap) {
                if (pair.second > maxCount) {
                    maxCount = pair.second;
                    bestLen = pair.first;
                }
            }
            total_len = bestLen;
            total_len_list.clear();
            // log("✅ 确认总长度: " + std::to_string(total_len));
        }

    } else if (frame_data_len == 3) {
            // 去除錯誤數據-下標超出范圍
        if (ascii_code < 0 && ascii_code > total_len){
            reset();
            return;
        }
        current_index = ascii_code;

    } else if (frame_data_len == 4) {
        char ch = asciiChar(ascii_code);
        if (ch != 0) {
            // log("🔤 解码字符: " + std::string(1, ch));
            if (current_index >= 0) {
                data_dict[current_index] = ch;
                // log("data_dict: " + mapToString(data_dict));
            } else {
                // log("❌ 解码失败，丢弃帧");
            }
        } else {
            // log("❌ 解码失败，丢弃帧");
        }
    }

    if (total_len > 0 && data_dict.size() >= static_cast<size_t>(total_len)) {
        std::string result;
        for (int i = 0; i < total_len; ++i) {
            auto it = data_dict.find(i);
            if (it != data_dict.end()) {
                result += it->second;
            }
        }
        // log("🎉 解码完成: " + result);
        {
            std::lock_guard<std::mutex> lock(targetDataMutex);
            target_data.push_back(result);
        }

        // log(std::string(50, '-'));
        has_check_repeat_flag = false;
        data_dict.clear();
        reset();
        targetDataCV.notify_all();
    }

    // log(std::string(50, '='));
}

void SmartConfig::handleCheckTargetData() {
    // 用于存储从 target_data 复制出来的数据，以便在锁外处理
    std::string wifiString_from_duplicate_check;
    std::vector<std::string> target_data_copy_for_majority_vote; // 复制 target_data 用于多数投票

    { // --- 关键区开始：在这里获取锁，仅保护对 target_data 的访问 ---
        std::lock_guard<std::mutex> lock(targetDataMutex);

        // 1. 快速重复检查
        if (target_data.size() > 1 && !has_check_repeat_flag) {
            // findDuplicateString 需要访问 target_data，所以它需要在锁的保护下调用
            wifiString_from_duplicate_check = findDuplicateString();
            if (!wifiString_from_duplicate_check.empty()) {
                // log("快捷算法：发现两个相同字符串，直接发送！");
                // 清空 target_data，因为已经找到了凭证
                target_data.clear();
                // 注意：handleWifiConnection 不能在这里调用，因为它可能会阻塞
            }
        }

        // 2. 如果快速检查没有找到重复项，并且 target_data 数量达到多数投票阈值
        if (wifiString_from_duplicate_check.empty() && target_data.size() > 5) {
            // 复制 target_data 的内容到局部变量，以便在锁外进行多数投票计算
            target_data_copy_for_majority_vote = target_data;
            // 清空 target_data，因为即将进行多数投票并处理
            target_data.clear();
            // 注意：handleWifiConnection 不能在这里调用
        }

        // --- 关键区结束：锁在这里自动释放 ---
    }

    // --- 锁外处理：在这里进行计算和调用其他函数，不会阻塞其他线程访问 target_data ---

    // 如果通过快速重复检查找到了凭证
    if (!wifiString_from_duplicate_check.empty()) {
        // log("快捷算法：连接WIFI");
        // 调用处理连接的函数，该函数不直接访问 target_data
        handleWifiConnection(wifiString_from_duplicate_check);
    }
    // 如果通过多数投票逻辑触发了处理 (快速检查未触发，并且复制了数据进行多数投票)
    else if (!target_data_copy_for_majority_vote.empty()) {
        // 在锁外对复制的数据进行多数投票计算
        std::map<std::string, int> countMap;
        for (const auto& str : target_data_copy_for_majority_vote) {
            countMap[str]++;
        }

        std::string bestString;
        int maxCount = 0;
        for (const auto& pair : countMap) {
            if (pair.second > maxCount) {
                maxCount = pair.second;
                bestString = pair.first;
            }
        }

        // log(std::string(50, '*'));
        // log("🎉 最佳候选凭证: " + bestString);
        // log(std::string(50, '*'));

        // 调用处理连接的函数，该函数不直接访问 target_data
        handleWifiConnection(bestString);
    }
}

// 处理 WiFi 连接
void SmartConfig::handleWifiConnection(const std::string& wifiString) {
    // log("➡️ 进入函数: handleWifiConnection");
    try {
        std::pair<std::string, std::string> credentials = parseWifiCredentials(wifiString);
        std::string ssid = credentials.first;
        std::string password = credentials.second;
        // log("📏 最终总长度: " + std::to_string(total_len));
        log("🎉 解码结果集合: " + vectorToString(target_data));
        log("🔑 尝试连接: SSID='" + ssid + ", " + "pwd=" + password);
        if (establishWifiConnection(ssid, password, "wlan0mon", "wlan0")) {
            broadcastAck(12345, "ACK");
            // log("✅ 连接成功，退出程序");
            // 设置退出标志
            g_exit_event = true;
            done = true;
            // 通知所有等待的线程
            targetDataCV.notify_all();
            queueCV.notify_all();
            // 停止pcap捕获
            if (pcap_handle) {
                pcap_breakloop(pcap_handle);
            }
            // log("已触发程序退出流程");
        } else {
            throw std::runtime_error("连接失败");
        }
    } catch (const std::exception& e) {
        // log("❌ 连接错误: " + std::string(e.what()));
        recoverToMonitor();
    }
    // log(std::string(50, '='));
}

// 执行 WiFi 连接
bool SmartConfig::establishWifiConnection(const std::string& ssid, const std::string& password, const std::string& monitorIface, const std::string& managedIface) {
    // log("➡️ 进入函数: establishWifiConnection");
    switchToManaged(monitorIface, managedIface);
    std::string cmd = "nmcli device wifi connect \"" + ssid + "\" password \"" + password + "\" ifname " + managedIface;
    int result = system(cmd.c_str());
    if (WIFEXITED(result)) {
        switch (WEXITSTATUS(result)) {
            case 0: 
                INTERFACE = managedIface;
                return true;
            case 4:
                // log("密码错误或信号弱");
                break;
            case 8:
                // log("请先启动NetworkManager服务");
                break;
            default:
                char buffer[256];
                snprintf(buffer, sizeof(buffer), "连接失败，错误码: %d", 
                        WEXITSTATUS(result));
                // log(buffer);
        }
    }
    return false;
}

// 恢复到监控模式
void SmartConfig::recoverToMonitor() {
    // log("➡️ 进入函数: recoverToMonitor");
    
    // 1. 停止现有的pcap捕获
    if (pcap_handle) {
        pcap_breakloop(pcap_handle);
        pcap_close(pcap_handle);
        pcap_handle = nullptr;
    }
    
    // 2. 切换到监控模式
    if (!switchToMonitor("wlan0", "wlan0mon", 10, wifi_channel)) {
        // log("❌ 无法恢复到监控模式！");
        g_exit_event = true;
        return;
    }
    
    // 3. 重置所有数据结构
    reset();
    total_len = 0;
    total_len_count = 0;
    current_index = -1;
    has_check_repeat_flag = false;
    frame_data.clear();
    data_dict.clear();
    target_data.clear();
    
    // 4. 重新初始化pcap
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_handle = pcap_open_live(INTERFACE.c_str(), 65535, 1, 100, errbuf);
    if (!pcap_handle) {
        // log("❌ 无法重新打开 pcap: " + std::string(errbuf));
        return;
    }
    
    // 5. 重新设置BPF过滤器
    struct bpf_program fp;
    if (pcap_compile(pcap_handle, &fp, "type data", 0, PCAP_NETMASK_UNKNOWN) == -1) {
        // log("❌ 编译BPF过滤器错误");
        return;
    }
    pcap_setfilter(pcap_handle, &fp);
    pcap_freecode(&fp);
    
    // 6. 重新启动捕获线程
    if (captureThread.joinable()) {
        captureThread.join();
    }
    captureThread = std::thread([this]() {
        {
            std::lock_guard<std::mutex> lock(threadNamesMutex);
            threadNames[std::this_thread::get_id()] = "捕获线程";
        }
        capturePackets(this->pcap_handle);
    });
    
    // log("✅ 已恢复监控模式并重启捕获");
}

// 查找重复的凭证字符串
std::string SmartConfig::findDuplicateString() {
    // // log("➡️ 进入函数: findDuplicateString");
    std::set<std::string> seen;
    for (const auto& str : target_data) {
        if (seen.find(str) != seen.end()) {
            return str;
        }
        seen.insert(str);
    }
    has_check_repeat_flag = true;
    return "";
}

bool SmartConfig::setChannel(const std::string& iface, int channel) {
    std::string cmd = "iwconfig " + iface + " channel " + std::to_string(channel);
    return system(cmd.c_str()) == 0;
}

void SmartConfig::scanChannels(const std::string& iface, 
                              const std::vector<int>& channels,
                              int duration) {
    packetCounts.clear();
    char errbuf[PCAP_ERRBUF_SIZE];
    std::cout << "Scanning channels..." << std::endl;
    for (int ch : channels) {
        if (!setChannel(iface, ch)) {
            std::cerr << "Failed to set channel " << ch << std::endl;
            continue;
        }

        currentChannel = ch;
        packetCounts[ch] = 0;

        // 打开捕获句柄
        pcap_t* handle = pcap_open_live(iface.c_str(), 65535, 1, 
                                      duration * 1000, errbuf);
        if (!handle) {
            std::cerr << "pcap_open_live failed: " << errbuf << std::endl;
            continue;
        }

        // 开始捕获
        const int count = pcap_dispatch(handle, 0, counterCallback, 
                                      reinterpret_cast<u_char*>(this));
        
        if (count == -1) {
            std::cerr << "pcap_dispatch error: " << pcap_geterr(handle) << std::endl;
        }

        pcap_close(handle);
        std::cout << "Channel " << ch << " packets: " << packetCounts[ch] << "\n";
    }

    // 选择最佳信道
    if (!packetCounts.empty()) {
        auto best = std::max_element(packetCounts.begin(), packetCounts.end(),
            [](auto& a, auto& b) { return a.second < b.second; });
        
        std::cout << "\nBest channel: " << best->first 
                 << " (" << best->second << " packets)\n";

        wifi_channel = best->first;
        setChannel(iface, best->first);
    }
}

// 数据包处理回调
void SmartConfig::counterCallback(u_char* user, const pcap_pkthdr* pkthdr, 
                                 const u_char* packet) {
    SmartConfig* self = reinterpret_cast<SmartConfig*>(user);
    
    // 基础长度检查（确保能读取前24字节）
    if (pkthdr->caplen < 24) return; // [3](@ref)
    self->packetCounts[self->currentChannel]++;
}


// 记录日志
void SmartConfig::log(const std::string& message) {
    // 获取当前线程名称
    std::string threadName;
    {
        std::lock_guard<std::mutex> lock(threadNamesMutex);
        auto it = threadNames.find(std::this_thread::get_id());
        threadName = (it != threadNames.end()) ? it->second : "未知线程";
    }

    // 生成时间戳
    auto now = std::chrono::system_clock::now();
    auto now_c = std::chrono::system_clock::to_time_t(now);
    std::string timestamp = std::ctime(&now_c);
    size_t pos = timestamp.find('\n');
    if (pos != std::string::npos) {
        timestamp.erase(pos);
    }

    // 构造带线程名称的日志消息
    std::string logMessage = "[" + timestamp + "] [" + threadName + "] - " + message;

    // 线程安全输出
    {
        std::lock_guard<std::mutex> lock(logMutex);
        if (logger.is_open()) {
            logger << logMessage << std::endl;
        }
        std::cout << logMessage << std::endl;
    }
}

// 整数向量转字符串
std::string SmartConfig::vectorToString(const std::vector<int>& vec) {
    std::ostringstream oss;
    for (size_t i = 0; i < vec.size(); ++i) {
        oss << vec[i];
        if (i < vec.size() - 1) {
            oss << ", ";
        }
    }
    return oss.str();
}

// 字符串向量转字符串
std::string SmartConfig::vectorToString(const std::vector<std::string>& vec) {
    std::ostringstream oss;
    for (size_t i = 0; i < vec.size(); ++i) {
        oss << vec[i];
        if (i < vec.size() - 1) {
            oss << ", ";
        }
    }
    return oss.str();
}

// 字符映射转字符串
std::string SmartConfig::mapToString(const std::map<int, char>& m) {
    std::ostringstream oss;
    for (const auto& pair : m) {
        char ch = pair.second;
        oss << pair.first << ": ";
        if (ch >= 32 && ch <= 126) {
            oss << "'" << ch << "'";
        } else {
            oss << "(非打印字符:" << static_cast<int>(ch) << ")";
        }
        oss << ", ";
    }
    // 移除末尾多余的 ", "
    std::string s = oss.str();
    if (!s.empty()) {
        s.resize(s.size() - 2);
    }
    return s;
}
// 信号处理函数
void signalHandler(int signum) {
    if (signum == SIGINT) {
        g_exit_event = true;
    }
}

// 主函数
int main() {
    SmartConfig config;
    config.log("➡️ 进入函数: main");
    std::signal(SIGINT, signalHandler);
    config.checkRoot();
    config.log("按 Ctrl+C 停止");

    if (config.isWifiConnected()) {
        config.log("已连接到 WiFi");
        return 0;
    }

    if (!config.switchToMonitor("wlan0", "wlan0mon", 10)) {
        config.log("❌ 无法切换到监控模式");
        return 1;
    }

    config.initializePcap();
    config.scanChannels("wlan0mon", {1, 6, 11}, 1);


    config.sniffing_thread = std::thread(&SmartConfig::startSniffing, &config);

    while (!g_exit_event) {
        {
            std::unique_lock<std::mutex> lock(config.targetDataMutex);
            config.targetDataCV.wait(lock, [&config] { return !config.target_data.empty() || g_exit_event; });
        }
        if (g_exit_event) break;
        // // log("📏 最终总长度: " + std::to_string(total_len));
        // // log("🎉 解码结果集合: " + vectorToString(target_data));
        config.handleCheckTargetData();
    }

    config.log("🛑 主线程退出");
    return 0;
}